import copy
from utils.conf import Response
from rest_framework.views import APIView
from ChatGPTServer.settings import formatResponseData, _request
import json


class TChat(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = []
    # 局部(本视图有效)权限类
    permission_classes = []

    def post(self, request, *args, **kwargs):
        """
        TChat接口
        """
        data = copy.deepcopy(formatResponseData)
        try:
            question = request.data.get("question")

            # 异常拦截
            if not question:
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            headers = {
                'Accept': 'application/json, text/plain, */*',
                'Content-Type': 'application/json',
                'Host': 'chat.68686.ltd',
                'Origin': 'https://chat.68686.ltd',
                'Referer': 'https://chat.68686.ltd/',
                'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
            }
            requestData = json.dumps({
                "prompt": question,
                "options": {},
            })
            response = _request.post(url='https://chat.68686.ltd/api/chat-process', headers=headers, data=requestData)

            answer = json.loads(response.text.split("\n").pop())["text"]

            data["data"]["answer"] = answer
            return Response(data=data, loggerMsg=f"TChat接口响应成功：question={question}")

        except Exception as e:
            return Response(data=data, loggerMsg=f"TChat接口响应失败：{e}", isError=True)
